﻿#if  NET6_0_OR_GREATER 
using Microsoft.AspNetCore.Builder;
using System;
using System.Collections.Generic;

namespace T.SF.Console
{
    public static class MiddlewareExtensions
    {
        public static IApplicationBuilder UseMiddlewares(
            this IApplicationBuilder builder)
        {
            System.Console.WriteLine($"System loading middleware, {nameof(CrosMiddleware)}");
            builder = builder.UseMiddleware<CrosMiddleware>();
            IApplicationBuilder pre = builder;
            var types = GetSGMiddlewares();
            if (types != null && types.Count > 0)
            {
                foreach (var type in types)
                {
                    if (type != null)
                    {
                        System.Console.WriteLine($"System loading middleware, {type.FullName}");
                        pre = pre.UseMiddleware(type);
                    }
                }

                return pre;
            }

            return pre;
        }

        private static List<Type> GetSGMiddlewares()
        {
            var types = new List<Type>();
            var sectionConfig = System.Configuration.ConfigurationManager.GetSection("Middlewares");
            if (sectionConfig != null)
            {
                var configs = sectionConfig as List<MiddlewareConfig>;
                if (configs != null)
                {
                    foreach (var config in configs)
                    {
                        try
                        {
                            System.Console.WriteLine($"System loading middleware, {config.type}");
                            types.Add(Type.GetType(config.type));
                            System.Console.WriteLine($"System loaded middleware, {config.type}");
                        }
                        catch { }
                    }
                }
            }

            return types;
        }
    }
}

#endif
